//
//  PlayerController.m
//  SimpleHappy
//
//  Created by lanou on 15/11/23.
//  Copyright © 2015年 RockyFung. All rights reserved.
//

#import "PlayerController.h"
#import "PlayerCell.h"
#import "Define.h"
#import "DetailController.h"
#import "PlayerModel.h"
#import "MJRefresh.h"
#import "SHDetailModel.h"

@interface PlayerController ()

@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) NSString *url;
@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation PlayerController

// 懒加载，一般用于上拉加载更多
- (NSMutableArray *)modelArray
{
    if (!_modelArray) {
        self.modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 清除tableViewCell自带线条
    self.tableView.separatorStyle = NO;
    
    // 数据请求
    self.url = @"http://api.yhouse.com/?r=v2/experience/list&app_type=1&page=1";
    [self setNetWorkRequestWithUrlString:self.url];
    
    // 下拉刷新
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headerAction)];
    // 下拉加载
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footerAction)];
    
}


#pragma mark - 数据请求
- (void)setNetWorkRequestWithUrlString:(NSString *)urlString
{
    [[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error) {
            NSLog(@"网络请求错误");
            return ;
        }
        
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        for (NSDictionary *dataDic in dic[@"data"]) {
            PlayerModel *model = [[PlayerModel alloc]init];
            [model setValuesForKeysWithDictionary:dataDic];
            [self.modelArray addObject:model];
        }
        // 刷新数据
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
//        NSLog(@"%@",self.modelArray);
    }]resume];
    
}

#pragma mark - 上拉加载更多，下拉刷新
// 下拉刷新
- (void)headerAction
{
    [self setNetWorkRequestWithUrlString:self.url];
    [self.tableView.header endRefreshing];
}
// 上拉加载更多
- (void)footerAction
{
    self.pageNum += 1;
    self.url = [NSString stringWithFormat:@"http://api.yhouse.com/?r=v2/experience/list&app_type=1&page=%ld",_pageNum+1];
    [self setNetWorkRequestWithUrlString:self.url];
    [self.tableView reloadData];
    [self.tableView.footer endRefreshing];
    
}



#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return KScreenWidth / 640 * 330;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    
    static NSString *cellIdentifier = @"cell";
    PlayerCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[PlayerCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    if (self.modelArray.count != 0) {
        cell.model = self.modelArray[indexPath.row];
    }
    return cell;
}

// 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailController *detailVc = [[DetailController alloc]init];
    PlayerModel *model = self.modelArray[indexPath.row];
    
    SHDetailModel *SHModel = [[SHDetailModel alloc]init];
    SHModel.picUrl = model.picUrl;
    SHModel.openUrl = model.openUrl;
    SHModel.title = model.title;
    detailVc.SHDetailModel = SHModel;
    
    detailVc.targetUrl = model.openUrl;
    detailVc.hidesBottomBarWhenPushed = YES;
    detailVc.isDiscover = YES;
    [self.navigationController pushViewController:detailVc animated:YES];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
